import os
import pandas as pd
from basic_params import Basic_var, path_instr


list_exchange = ['SHFE']  # ['DCE', 'SHFE']

dic_excg_instr = {}  # key:exchange value: 合约集合
dic_excg_fture = {}  # key:exchange value: 品种列表
dic_excg_fture_instr = {}  # key:exchange value:dict 各品种对应合约


def init_dicts():
    global dic_excg_instr
    global dic_excg_fture
    global dic_excg_fture_instr
    dic_excg_instr = {}
    dic_excg_fture = {}
    dic_excg_fture_instr = {}


def change_dicts_and_make_dirs():
    for i in list_exchange:  # 从exg_instrID_list，按交易所分类整理出所有instrID
        dic_excg_instr[i] = [
            x.split('.')[1] for x in Basic_var.excg_instrID_list if x.split('.')[0] == i]

    for i in list_exchange:  # 从exg_instrID_list，按交易所分类整理出所有future
        dic_excg_fture[i] = list(set([''.join(filter(str.isalpha, x.split('.')[
            1])) for x in Basic_var.excg_instrID_list if x.split('.')[0] == i]))

    for i in list_exchange:  # 从dict_exchange_instr，按交易所分类整理出future:instr字典
        dic = {}
        for j in dic_excg_fture[i]:  # 遍历对应交易所中各个品种
            dic[j] = set(x for x in dic_excg_instr[i]
                         if ''.join(filter(str.isalpha, x)) == j)   # 键为各个品种，键值为对应品种全部合约字典
        dic_excg_fture_instr[i] = dic

    for i in dic_excg_fture_instr.keys():  # i = exchange
        if not os.path.exists(path_instr + i):
            os.mkdir(path_instr + i)  # 合成后的单个合约文件存放路径path_out后明细交易所路径
        else:
            pass
        for j in dic_excg_fture_instr[i].keys():  # j = future
            if not os.path.exists(path_instr + i + '\\' + j):
                os.mkdir(path_instr + i + '\\' + j)  # path_out后明细交易所路径后继续明细品种
            else:
                pass
            for k in dic_excg_fture_instr[i][j]:  # k = instrument
                if not os.path.exists(path_instr + i + '\\' + j + '\\' + k):
                    # path_out明细品种后继续明细合约
                    os.mkdir(path_instr + i + '\\' + j + '\\' + k)
                else:
                    pass


def update_one_instr(dataframeDic, excg: str, fture: str, instr: str):
    path = path_instr + excg + '\\' + fture + '\\'+instr + '\\'
    if len(os.listdir(path)) == 0:  # 如果该合约文件夹路径下无文件，则进行写入
        df = dataframeDic[instr]
        df.to_parquet(path + instr)
    else:
        df = pd.read_parquet(path + instr)
        df_today = dataframeDic[instr]
        df = pd.concat([df, df_today])
        df.to_parquet(path + instr)


def update_all_instr(dataframeDic):
    for exchange in dic_excg_fture_instr.keys():
        for future in dic_excg_fture_instr[exchange].keys():
            for instrument in dic_excg_fture_instr[exchange][future]:
                update_one_instr(dataframeDic, exchange, future, instrument)


def get_today_maxoi_instrID(dataframeDic, instrList):
    '''
    获得最大持仓合约名称
    '''
    oi_instr_dict = {}  # key:open_interest amount value:instr 各个合约持仓情况
    for instr in instrList:  # 遍历各个合约j
        df = dataframeDic[instr]
        # 获得各个合约数据中最后一刻持仓量
        oi_instr_dict[df['OpenInterest'].tail(1).values[0]] = instr
    return oi_instr_dict[max(oi_instr_dict.keys())]


def update_main_instr(dataframeDic):
    '''
    按照当日最大持仓跟新不同品种的主力合约
    '''
    for exchange in dic_excg_fture.keys():
        for future in dic_excg_fture[exchange]:  # 遍历交易所中的各个品种
            path = path_instr + exchange + '/' + future + '/'  # 各个合约数据的路径前缀
            instr_l = list(dic_excg_fture_instr[exchange][future])  # 获得对应合约列表
            # 合成主力合约逻辑：判断是否是第一次合成 如非第一次合成则由上次合成日期开始计算
            if not os.path.exists(path + future+'m'):
                maxoi_instr = get_today_maxoi_instrID(
                    dataframeDic, instr_l)
                os.mkdir(path + future+'m')
                dataframeDic[maxoi_instr].to_parquet(
                    path + future+'m'+'\\' + future+'m')  # 保存主力合约数据
            else:  # 如果之前保存过：
                df = pd.read_parquet(path + future+'m'+'\\' + future+'m')
                maxoi_instr = get_today_maxoi_instrID(
                    dataframeDic, instr_l)
                df_today = dataframeDic[maxoi_instr]
                df = pd.concat([df, df_today], ignore_index=True)
                df.to_parquet(path + future+'m'+'\\' + future+'m')  # 保存主力合约数据


def UpdateInstrs_after_store(dataframeDic):
    init_dicts()
    change_dicts_and_make_dirs()
    update_all_instr(dataframeDic)
    update_main_instr(dataframeDic)
